package com.loyal.mwm.libs.api

import com.loyal.client.error.ExceptHelper
import com.loyal.mwm.data.ResponseData
import kotlinx.coroutines.*

open class BaseRepository {

    private lateinit var contextScope: CoroutineScope

    protected suspend fun <T : Any> request(
        what: Int = 2,
        tag: Any? = null,
        block: suspend () -> T?
    ): ResponseData<T?> {
        return try {
            val t = withContext(Dispatchers.IO) {
                contextScope = this
                block.invoke()
            }
            ResponseData(
                success = true,
                what = what,
                data = t,
                tag = tag
            )
        } catch (e: Exception) {
            val error = if (e is CancellationException)
                "已取消操作"
            else ExceptHelper.get(e)
            ResponseData(
                what = what,
                message = error,
                error = true,
                tag = tag
            )
        }
    }

    open fun updateBaseUrl() {
    }

    fun cancelRequest() {
        if (!this::contextScope.isInitialized)
            return
        if (contextScope.isActive)
            contextScope.cancel()
    }
}